from numbers import polygonal
from itertools import chain

def splitDigits(n):
    s = str(n)
    return (s[:2], s[-2:])

def findTrail(prefix, list, trail):
    if 0 == len(list):
        if prefix == trail[0]:
            trail.append(prefix)
            print trail
        return

    for i in xrange(len(list)):
        d = list[i]
        for postfix in d.get(prefix, []):
            findTrail(postfix, list[:i] + list[i+1:], trail + [prefix])
    
L = list() 

for s in [3,4,5,6,7,8]:
    Ds = dict()
    L.append(Ds)

    for n in polygonal(s):
        if n > 9999: break

        if n >= 1000:
            (pre,post) = splitDigits(n)
            prePosts = Ds.setdefault(pre, list())
            prePosts.append(post)
            
for prefix in [str(x) for x in xrange(10, 100)]:
    findTrail(prefix, L, [])
            
        

            